import {ref,reactive,onMounted} from 'vue'
import {getRoleListApi} from '@/api/role'
import {getRoleIdApi,updateUserRoleApi} from '@/api/user'
import useInstance from '@/hooks/useInstance';
export const useAssignRole = (dialog, onClose, onShow, emit) => {
  const { global } = useInstance()
   //被分配角色的用户id
   const selecUserId = ref('');
   //选择的角色id
   const selectRoleId = ref('');
   //确定
 //角色列表查询参数
 const parms = reactive({
  current: 1,
  size: 4,
  userId:'',
  total: 0
})
//角色列表数据
const roleList = reactive({
  list: []
})
 //获取列表的数据
 const getRoleList = async () => {
  let res = await getRoleListApi(parms)
  console.log("🚀 ~ file: useAssignRole.js:25 ~ getRoleList ~ res:", res)
  if (res && res.code == 200) {
      roleList.list = res.data.page.records;
      parms.total = res.data.page.total;
  }
}
  const confirm = async() => {
    if(!selectRoleId.value){
      global.$message({ message: '请选择角色', type: 'warning' })
      return;
  }
let param = {
  accountId:selecUserId.value,
  roleId:selectRoleId.value
}
  let res = await updateUserRoleApi(param)
        if (res && res.code == 200) {
            global.$message({ message: '分配成功', type: 'success' })
            //关闭弹框
            onClose();
        }
    onClose()
  }

  const show = async(row) => {
    selecUserId.value = row.accountId
    selectRoleId.value = ''
    let res = await getRoleIdApi(row.accountId)
        if (res && res.data) {
            selectRoleId.value = res.data.roleId
        }
    dialog.title = `为【${row.username}】分配角色`
    console.log("🚀 ~ file: useAssignRole.js:44 ~ show ~ selectRoleId.value:", selectRoleId.value)
    onShow()
  }
    //页容量改变时触发
    const sizeChange = (size) => {
      parms.size = size;
      getRoleList()
  }
  //页数改变时触发
  const currentChange = (page) => {
      parms.current = page;
      getRoleList()
  }
  //单选按钮点击事件
  const getSlectRole = (row) => {
    console.log('--------------选取角色------------',row.roleId);
      //设置选中的角色id
      selectRoleId.value = row.roleId
  }
  onMounted(() => {
    getRoleList()
  })
  return{
    confirm,
    show,
    parms,
    roleList,
    sizeChange,
    currentChange,
    getSlectRole,
    selecUserId,
    selectRoleId
  }
}